package service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;

import controller.Domain;
import controller.Utils;



public class Whois extends Thread{
	Domain domain;
	public Whois(Domain domain)
	{
		this.domain=domain;
		this.start();
	}
	
	public void run()
	{
		try {
			Process process;
			BufferedReader buf;
			String line;
			String whois="";
			if(!Utils.checkSubDomain(domain.getName()))
			{
	        	process = Runtime.getRuntime().exec("whois "+domain.getName());
				buf = new BufferedReader(new InputStreamReader(
				process.getInputStream()));

				while ((line = buf.readLine()) != null) {
					whois += line+"<br/>";
				}
			} else {
				process = Runtime.getRuntime().exec("whois "+Utils.returnSubDomainTo(domain.getName()));
				buf = new BufferedReader(new InputStreamReader(
				process.getInputStream()));

				while ((line = buf.readLine()) != null) {
					whois += line+"<br/>";
				}
			}
			
			
			String ip = "";
			try {
				InetAddress giriAddress = java.net.InetAddress.getByName(domain.getName());
				ip = giriAddress.getHostAddress();
			} catch (Exception e) {
				// TODO: handle exception
			}
         
			process = Runtime.getRuntime().exec("whois "+ip);
			buf = new BufferedReader(new InputStreamReader(
			process.getInputStream()));
			
			String wip="";
			while ((line = buf.readLine()) != null) {
				wip += line+"<br/>";
			}
			
			domain.setWhois(whois);

			domain.setIp(ip);
			domain.setWhoisIp(wip);
        

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

	}
//	public static void main( String args[])
//	{
//		new Whois("ketoan.org");
//	}
}
